const logkey = 'xone-recorder'

let stream
let buffer
let mediaRecorder
let recording

let xrecorder = {
  async screenRecordStart(screen={}, mic, avideos=[], aaudios=[], {showError=true, errorMsg='录屏失败', fail}={}) {
    console.log(logkey, 'screenRecordStart')
    this.screenRecordRecordingPrepare = true
    this.screenRecordRecording = false
    let videos = avideos, audios = aaudios
    let displayMedia
    try {
      if(screen) {
        if(!window.navigator.mediaDevices || !window.navigator.mediaDevices.getDisplayMedia){
          if(showError) uni.$x.notify.showToast(errorMsg)
          throw '不支持'
        } 
        
        displayMedia = await window.navigator.mediaDevices.getDisplayMedia({
          video : screen?{
            width : 1024,
            height : 768,
            frameRate : 15,
            facingMode : 'enviroment',
            ...screen
          }:null, 
          audio : mic
        })

        videos = [...displayMedia.getVideoTracks(), ...avideos]
        audios = [...displayMedia.getAudioTracks(), ...aaudios]
      }

      this.screenRecordBuffer = []
      if(audios.length) {
        this.screenRecordAudioContext = new AudioContext()
        this.screenRecordAudioContextDest = this.screenRecordAudioContext.createMediaStreamDestination()
        audios.forEach(v=>{
          if(!v) return
          this.screenRecordAudioContext.createMediaStreamSource(new MediaStream([v.getAudioTracks()[0]])).connect(this.screenRecordAudioContextDest)
        })
        let audioTrack = this.screenRecordAudioContextDest.stream.getAudioTracks()[0]
        videos.push(audioTrack)
      }

      this.screenRecordStream = new MediaStream([...videos])
      this.screenRecordRecorder = new MediaRecorder( this.screenRecordStream, { mimeType : 'video/webm'})

      this.screenRecordRecorder.ondataavailable = e=>{
        if(e && e.data && e.data.size > 0 && this.screenRecordBuffer){
          this.screenRecordBuffer.push(e.data)
        }
      };
      this.screenRecordRecorder.onstart = e=>{
        console.log(logkey, 'screenRecordStart onstart')
        this.screenRecordRecording = true
      }
      this.screenRecordRecorder.onstop = e=>{
        console.log(logkey, 'screenRecordStart onstop')
        this.screenRecordRecording = false
        this.screenRecordRecordingPrepare = false
      }
      this.screenRecordRecorder.onerror = e=>{
        console.log(logkey, 'screenRecordStart onerror', e)
        if(fail&&fail()===true) return
        if(showError) uni.$x.notify.showToast(errorMsg)
        this.screenRecordRecording = false
        this.screenRecordRecordingPrepare = false
        this.screenRecordClear()
      }
      this.screenRecordRecorder.start(10);
      console.log(logkey, 'screenRecordStart start')
    }catch(e) {
      console.log(logkey, 'error', e)
      if(showError) uni.$x.notify.showToast(errorMsg)
      this.screenRecordClear()
      throw '参数错误'
    }
  },
  screenRecordAddAudio(audio) {
    this.screenRecordAudioContext.createMediaStreamSource(new MediaStream([audio.getAudioTracks()[0]])).connect(this.screenRecordAudioContextDest)
  },
  screenRecordClear() {
    this.screenRecordBuffer = null
    if(this.screenRecordAudioContextDest) {
      this.screenRecordAudioContextDest = null
    }
    if(this.screenRecordAudioContext) {
      this.screenRecordAudioContext.close()
      this.screenRecordAudioContext = null
    }
    if(this.screenRecordStream) {
      this.screenRecordStream.getTracks().forEach(v=>v.stop())
      this.screenRecordStream = null
    }
    if(this.screenRecordRecorder) {
      if(this.screenRecordRecorder.state === 'active')this.screenRecordRecorder.stop()
      this.screenRecordRecorder = null
    }
  },
  screenRecordStop() {
    let ret = false
    this.screenRecordRecordingPrepare = false
    
    if(this.screenRecordRecording) {
      ret = new Blob(this.screenRecordBuffer, {type: 'video/webm'})
      this.screenRecordRecorder.stop()
    }

    this.screenRecordClear()
    return ret
  },
}

export default function($x, {
	xrecorderExtend
}={}, app) {
	Object.assign(xrecorder, xrecorderExtend||{})
	$x.xrecorder = xrecorder
}